package storage

import (
    "context"
    "fmt"

    "google.golang.org/protobuf/proto"

    "cing.io/cing-api/task"
    builtins "cing.io/cing/internal/builtins/tasktype"
)

func getTaskTypeKey(taskType string) string {
    return fmt.Sprintf("%s/%s", taskTypePrefix, taskType)
}

func PutTaskType(taskType *task.TaskType) error {
    key := getTaskTypeKey(taskType.Name)

    bytes, err := proto.Marshal(taskType)
    if err != nil {
        return err
    }

    _, err = Etcd().Put(context.TODO(), key, string(bytes))
    if err != nil {
        return err
    }
    return nil
}

func GetTaskType(name string) *task.TaskType {
    taskType := builtins.GetTaskType(name)
    if taskType != nil {
        return taskType
    }

    key := getTaskTypeKey(name)

    resp, err := Etcd().Get(context.TODO(), key)
    if err != nil {
        return nil
    }

    taskType = &task.TaskType{}
    err = proto.Unmarshal(resp.Kvs[0].Value, taskType)
    if err != nil {
        return nil
    }
    return taskType
}

func DeleteTaskType(name string) error {
    key := getTaskTypeKey(name)

    _, err := Etcd().Delete(context.TODO(), key)
    if err != nil {
        return err
    }

    return nil
}
